import { elUpdateByQueryForMigration } from '../database/engine';
import { READ_INDEX_STIX_DOMAIN_OBJECTS } from '../database/utils';

export const up = async (next) => {
  const updateQuery = {
    script: {
      source:
          "if (!ctx._source.containsKey('x_opencti_cvss_base_score')) { ctx._source.x_opencti_cvss_base_score = ctx._source.x_opencti_base_score; ctx._source.remove('x_opencti_base_score'); } "
          + "if (!ctx._source.containsKey('x_opencti_cvss_base_severity')) { ctx._source.x_opencti_cvss_base_severity = ctx._source.x_opencti_base_severity; ctx._source.remove('x_opencti_base_severity'); } "
          + "if (!ctx._source.containsKey('x_opencti_cvss_attack_vector')) { ctx._source.x_opencti_cvss_attack_vector = ctx._source.x_opencti_attack_vector; ctx._source.remove('x_opencti_attack_vector'); } "
          + "if (!ctx._source.containsKey('x_opencti_cvss_integrity_impact')) { ctx._source.x_opencti_cvss_integrity_impact = ctx._source.x_opencti_integrity_impact; ctx._source.remove('x_opencti_integrity_impact'); } "
          + "if (!ctx._source.containsKey('x_opencti_cvss_availability_impact')) { ctx._source.x_opencti_cvss_availability_impact = ctx._source.x_opencti_availability_impact; ctx._source.remove('x_opencti_availability_impact'); } "
          + "if (!ctx._source.containsKey('x_opencti_cvss_confidentiality_impact')) { ctx._source.x_opencti_cvss_confidentiality_impact = ctx._source.x_opencti_confidentiality_impact; ctx._source.remove('x_opencti_confidentiality_impact'); } ",
    },
    query: {
      bool: {
        must: [
          { term: { 'entity_type.keyword': { value: 'Vulnerability' } } },
        ],
      },
    },
  };
  await elUpdateByQueryForMigration(
    '[MIGRATION] Renaming Vulnerability attributes',
    [READ_INDEX_STIX_DOMAIN_OBJECTS],
    updateQuery
  );
  next();
};

export const down = async (next) => {
  next();
};
